//
//  OrderStockEdit.m
//  iHedron
//
//  Created by George Radev on 2011-08-07.
//  Copyright 2011 I Me Mine. All rights reserved.
//

#import "OrderStockEdit.h"


@implementation OrderStockEdit
@synthesize qtyText, priceText;

-(void) setStock:(Stock*) _stock{
	stock = [_stock retain];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	UIBarButtonItem* rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Запиши" 
				style:UIBarButtonItemStyleDone target:self action:@selector(doUpdateStock)];
	self.navigationItem.rightBarButtonItem = rightButton;
	[rightButton release];
	
	editableStock = [[Stock alloc] init];
	if(stock){
		editableStock.sname = stock.sname;
		editableStock.qty = stock.qty;
		editableStock.price = stock.price;
	}
	
	self.title= editableStock.sname;
	qtyText.text= [NSString stringWithFormat:@"%d", editableStock.qty ];
	priceText.text= [NSString stringWithFormat:@"%.4f", editableStock.price ];
	
	[qtyText becomeFirstResponder];
}

- (void)dealloc {
	if(stock){
		[stock release];
	}
	[editableStock release];
    [super dealloc];
}

-(void)doUpdateStock{
	
	{// parse price
		int iValue;
		NSScanner* scanner = [NSScanner scannerWithString: qtyText.text];
		bool isCorrect = [scanner scanInt:&iValue];
		
		if(isCorrect){
			editableStock.qty = iValue;
		}else{
			UIAlertView *alert = [[UIAlertView alloc] init];
			[alert setTitle:@"Грешка"];
			[alert setMessage:@"Моля, попълнете коректнo количество!"];
			[alert setDelegate:self];
			[alert addButtonWithTitle:@"Ок"];
			[alert show];
			[alert release];
			return;
		}
	}
	
	{// parse price
		double value;
		NSScanner* scanner = [NSScanner scannerWithString: priceText.text];
		bool isCorrect = [scanner scanDouble:&value];
			
		if(isCorrect){
			editableStock.price = value;
		}else{
			UIAlertView *alert = [[UIAlertView alloc] init];
			[alert setTitle:@"Грешка"];
			[alert setMessage:@"Моля, попълнете коректна цена!"];
			[alert setDelegate:self];
			[alert addButtonWithTitle:@"Ок"];
			[alert show];
			[alert release];
			return;
		}
	}
	if(stock){
		stock.qty = editableStock.qty;
		stock.price = editableStock.price;
	}
	[self.navigationController popViewControllerAnimated:TRUE];		
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}
@end
